﻿using CatHouse.DAL;
using CatHouse.Models;
using System.Linq;
using System.Web.Mvc;

namespace CatHouse.Controllers
{
    public class AdminController : Controller
    {
        private readonly PetShopContext db = new PetShopContext();

        [HttpGet]
        public ActionResult Login()
        {
            var user = Session["LoginUser"] as UserModel;
            if (user != null && user.Name != null)
            {
                return RedirectToAction("Index", "Home");
            }

            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public string Login(LoginModel m)
        {
            if (!ModelState.IsValid)
            {
                return Lib.Lang.ModelInvalid;
            }

            var user = db.Users.FirstOrDefault(item => item.UserEmail == m.UserEmail);

            if (user == null)
            {
                return "Không tìm thấy tài khoản.";
            }
            else
            {
                if (user.Password != m.Password)
                {
                    return "Mật khẩu không đúng";
                }
                else
                {
                    Session["LoginUser"] = user;
                    return null;
                }
            }
        }

        [HttpGet]
        public ActionResult Logout()
        {
            Session["LoginUser"] = null;
            var refer = Request.UrlReferrer != null ? Request.UrlReferrer.ToString() : Request.UserHostAddress;
            return Redirect(refer);
        }
    }
}